package com.derive.education_service.web.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.derive.education_service.common.global.Paper;
import com.derive.education_service.common.global.ResponseMessage;
import com.derive.education_service.entity.Content;
import com.derive.education_service.entity.ContentResources;
import com.derive.education_service.entity.Platform;
import com.derive.education_service.mapper.ContentMapper;
import com.derive.education_service.mapper.ContentResourcesMapper;
import com.derive.education_service.mapper.PlatformMapper;
import com.derive.education_service.utils.MyFileUtils;
import com.derive.education_service.web.content.bean.dto.ContentAddDto;
import com.derive.education_service.web.content.bean.dto.ContentUpDto;
import com.derive.education_service.web.content.bean.dto.QueryParam;
import com.derive.education_service.web.content.service.ContentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 内容操作接口
 */
@Service
@Slf4j
public class ContentServiceImpl implements ContentService {

    @Autowired
    private MyFileUtils myFileUtils;

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private ContentResourcesMapper contentResourcesMapper;

    @Autowired
    private PlatformMapper platformMapper;

    /**
     * 添加内容信息 -- 包括资源信息，没有资源则后面再添加也可
     * logo+资源+内容信息
     * 校验主营业务唯一标识code是否存在 -- 不能乱来
     * 校验机构是否存在 -- 不能乱来(默认为1)
     * @param logoFile
     * @param files
     * @param contentAddDto
     * @return
     */
    @Override
    public ResponseMessage addBusinessContent(MultipartFile logoFile, List<MultipartFile> files, ContentAddDto contentAddDto) {
        // 校验是否存在主营业务
        int code = contentMapper.checkBusiness(contentAddDto.getCode());
        if (code <= 0) {
            return ResponseMessage.createByErrorMessage("主营业务不存在，请检查");
        }
        // 校验是否存在机构
        Platform platform = platformMapper.selectById(contentAddDto.getPlatformId());
        if (platform == null) {
            return ResponseMessage.createByErrorMessage("不存在该机构，请检查");
        }
        // 基础校验通过，数据填充
        Content content = new Content();
        BeanUtils.copyProperties(contentAddDto, content);

        try {
            // logo文件上传 -- 必传
            if (logoFile != null && !logoFile.isEmpty()) {
                // 存在
                ResponseMessage logoR = myFileUtils.uploadFile(logoFile, "contentLogo");
                if (logoR.getStatus() == 0) {
                    // 上传文件成功，添加地址
                    content.setContentLogo(String.valueOf(logoR.getData()));
                    // 插入数据
                    content.setUserId(1); // 就是管理员id
                    content.setCreateTime(new Date());
                    content.setUpdateTime(new Date());
                    int row = contentMapper.insert(content);
                    if (row <= 0) {
                        return ResponseMessage.createByErrorMessage("新增内容异常");
                    }
                    // 继续新增资源
                } else {
                    // 失败
                    return ResponseMessage.createByErrorMessage("logo文件上传失败{[addBusinessContent-73]}");
                }
            } else {
                return ResponseMessage.createByErrorMessage("logo文件需上传");
            }

            // 资源信息上传--选填-有则传，没有则为空，后续再单独传 -- 直接添加
            if (files != null && !files.isEmpty() && files.size() != 0) {
                int row = 0;
                for (MultipartFile f : files) {
                    ResponseMessage r = myFileUtils.uploadFile(f, "contentRes");
                    if (r.getStatus() == 0) {
                        // 上传资源成功
                        ContentResources contentResources = new ContentResources();
                        contentResources.setContentId(content.getContentId()); // 新增成功后会自动更新id
                        contentResources.setCrUrl(String.valueOf(r.getData()));
                        contentResources.setAdminId(1);// 默认是1
                        contentResources.setCreateTime(new Date());
                        contentResources.setUpdateTime(new Date());

                        row += contentResourcesMapper.insert(contentResources);
                    } else {
                        // 上传失败
                        return ResponseMessage.createByErrorMessage("资源文件节点上传失败{[addBusinessContent]}");
                    }
                }
                if (row <= 0) {
                    return ResponseMessage.createByErrorMessage("内容新增成功，资源新增异常");
                } else {
                    return ResponseMessage.createBySuccessMessage("内容新增成功");
                }
            } else {
                // 没有资源，直接退出
                return ResponseMessage.createBySuccessMessage("新增内容成功，无资源新增，后续需添加资源");
            }
        } catch (IOException e) {
            log.error("文件上传异常{[addBusinessContent]}");
            e.printStackTrace();
            return ResponseMessage.createByErrorMessage("文件上传异常{[addBusinessContent]}");
        }
    }

    /**
     * 删除内容信息 -- 存在资源，连带删除资源
     * @param contentId
     * @return
     */
    @Override
    public ResponseMessage delBusinessContent(int contentId) {
        // 遍历内容所带资源
        QueryWrapper<ContentResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId);
        List<ContentResources> contentResourcesList = contentResourcesMapper.selectList(queryWrapper);

        // 获取内容logo地址
        String logoUrl = contentMapper.selectById(contentId).getContentLogo();
        // 删除logo资源
        ResponseMessage logoR = myFileUtils.delFile(logoUrl);
        if (logoR.getStatus() == 1) {
            // 失败退出
            log.error("删除内容logo异常");
            return ResponseMessage.createByErrorMessage("删除内容logo异常");
        }
        // 删除成功则删除信息
        int row = contentMapper.deleteById(contentId);
        if (row <= 0) {
            // 删除失败 -- 大件事
            return ResponseMessage.createByErrorMessage("删除内容信息失败，联系管理员{[]}");
        }
        // 删除资源图片 -- 信息
        for (ContentResources c : contentResourcesList) {
            ResponseMessage resR = myFileUtils.delFile(c.getCrUrl());
            if (resR.getStatus() == 1) {
                // 失败退出
                log.error("删除资源内容异常");
                return ResponseMessage.createByErrorMessage("删除资源内容异常");
            }
            // 成功则一一删除记录
            int code = contentResourcesMapper.deleteById(c.getCrId());
            if (code <= 0) {
                return ResponseMessage.createByErrorMessage("删除内容资源图片失败，联系管理员{[]}");
            }
        }
        return ResponseMessage.createBySuccessMessage("删除成功");
    }

    /**
     * 更新内容信息 -- 支持改内容+logo
     * @param file
     * @param contentUpDto
     * @return
     */
    @Override
    public ResponseMessage upBusinessContent(MultipartFile file, ContentUpDto contentUpDto) {
        // 上传新文件
        Content content = new Content();
        BeanUtils.copyProperties(contentUpDto, content);
        // 判断文件是否更改
        if (file != null && !file.isEmpty()) {
            // 执行更改 -- 先删除
            String url = contentMapper.selectById(contentUpDto.getContentId()).getContentLogo();
            // 删除资源
            ResponseMessage r = myFileUtils.delFile(url);
            if (r.getStatus() == 1) {
                // 失败退出
                log.error("更新内容logo失败");
                return r;
            }
            try {
                ResponseMessage ar = myFileUtils.uploadFile(file, "contentLogo");
                if (ar.getStatus() == 0) {
                    // 上传成功，更新地址
                    content.setContentLogo(String.valueOf(ar.getData()));
                    content.setUpdateTime(new Date());
                } else {
                    return ResponseMessage.createByErrorMessage("文件上传异常");
                }
            } catch (IOException e) {
                log.error("文件上传异常{[upBusinessContent]}");
                e.printStackTrace();
                return ResponseMessage.createByErrorMessage("更新内容logo文件上传异常{[upBusinessContent]}");
            }
        }
        // 不更新文件
        // 执行更新
        content.setUpdateTime(new Date());
        int row = contentMapper.updateById(content);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("更新异常");
        }
        return ResponseMessage.createBySuccess("更新成功");
    }

    /**
     * 查询内容详情信息 -- 带内容信息+资源信息
     * @param contentId
     * @return
     */
    @Override
    public ResponseMessage getContentById(int contentId) {
        // 内容信息
        Content content = contentMapper.selectById(contentId);

        if (content == null) {
            return ResponseMessage.createByErrorMessage("内容实体不存在");
        }

        // 资源信息
        QueryWrapper<ContentResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId);
        List<ContentResources> contentResourcesList = contentResourcesMapper.selectList(queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("contentInfo", content);
        map.put("resList", contentResourcesList);

        return ResponseMessage.createBySuccess(map);
    }

    /**
     * 查询内容列表信息 -- 分页，条件查询(内容资源信息，查询资源详情的时候才需要用)
     * @param queryParam
     * @return
     */
    @Override
    public Paper<Map<String, Object>> getContentList(QueryParam queryParam) {
        Page<Content> page = new Page<>();
        page.setCurrent(queryParam.getCurrent());
        page.setSize(queryParam.getSize());

        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("platform_id", 1); // 机构 默认1
        queryWrapper.eq("code", queryParam.getCode());

        if (queryParam.getContentTitle() != null
                && !queryParam.getContentTitle().isEmpty()) {
            queryWrapper.like("content_title", queryParam.getContentTitle());
        }

        queryWrapper.orderByDesc("create_time"); // 倒序

        // 内容列表信息
        Page<Content> contentPage = contentMapper.selectPage(page, queryWrapper);
        // 绑定资源信息
        List<Map<String, Object>> list = new ArrayList<>();
        for (Content c : contentPage.getRecords()) {
            QueryWrapper<ContentResources> resourcesQueryWrapper = new QueryWrapper<>();
            resourcesQueryWrapper.eq("content_id", c.getContentId());
            List<ContentResources> resourcesList = contentResourcesMapper.selectList(resourcesQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("contentInfo", c);
            map.put("resList", resourcesList);

            list.add(map);
        }


        // 分页系数
        Paper<Map<String, Object>> paper = new Paper<>();
        paper.setCurrent(contentPage.getCurrent());
        paper.setSize(contentPage.getSize());
        paper.setPages(contentPage.getPages());
        paper.setData(list);
        paper.setTotal(contentPage.getTotal());

        return paper;
    }
}
